<template>
  <main>

    <!-- 通用头部 -->
    <c-header :menus="[]" />

    <!-- 报名内容 -->
    <am-container style="min-height:700px">
      <am-row>

        <!-- 报名表单 -->
        <am-col :span="12">
          <form class="am-form am-form-horizontal dg-art">
            <fieldset>
              <legend>报名页</legend>

              <!-- 门头图片storeMainPic -->
              <div :class="['am-form-group', 'am-form-group-sm', { 'am-form-error': !validator.storeMainPic.vld }]">
                <label class="am-u-sm-12 am-u-md-2 am-form-label" for="storeMainPic">门头图片</label>
                <div class="am-u-sm-12 am-u-md-6">
                  <upload-img ref="smpic"
                    :imgCount.sync="storeMainPicCount"
                    :isGoVali="false"
                    :imgPath.sync="applyForm.storeMainPic" />
                  <template v-if="!validator.storeMainPic.vld">
                    <span class="am-icon-times"></span>
                    <small class="am-text-danger">{{ validator.storeMainPic.msg }}</small>
                  </template>
                </div>
                <div class="am-u-end"></div>
              </div>

              <!-- 店面图片storePic -->
              <div :class="['am-form-group', 'am-form-group-sm', { 'am-form-error': !validator.storePic.vld }]">
                <label class="am-u-sm-12 am-u-md-2 am-form-label" for="storePic">店面图片</label>
                <div class="am-u-sm-12 am-u-md-6">
                  <am-scrollbar :height="300" :auto-hide="false">
                    <upload-img ref="pics"
                      :imgCount.sync="storePicCount"
                      :isGoVali="false"
                      :imgPath.sync="applyForm.storePic"
                      :multiple="true"
                      :showFileList="true"
                      :listType="'picture'" />
                      <template v-if="!validator.storePic.vld">
                      <span class="am-icon-times"></span>
                      <small class="am-text-danger">{{ validator.storePic.msg }}</small>
                    </template>
                  </am-scrollbar>
                </div>
                <div class="am-u-sm-12 am-u-md-4">
                  <p class="am-text-danger" v-if="!validator.storePic.vld">{{ validator.storePic.msg }}</p>
                </div>
                <div class="am-u-end"></div>
              </div>

              <!-- 三维家 -->
              <div :class="['am-form-group', 'am-form-group-sm', 'am-form-feedback', { 'am-form-icon am-form-error': !validator.svjiaNo.vld }]">
                <label class="am-u-sm-12 am-u-md-2 am-form-label" for="svjiaNo">三维家帐号</label>
                <div class="am-u-sm-12 am-u-md-5">
                  <am-input placeholder="三维家帐号" v-model="applyForm.svjiaNo" />
                  <template v-if="!validator.svjiaNo.vld">
                    <span class="am-icon-times"></span>
                    <small class="am-text-danger">{{ validator.svjiaNo.msg }}</small>
                  </template>
                </div>
                <div class="am-u-end"></div>
              </div>


              <!-- 门店名称 -->
              <div :class="['am-form-group', 'am-form-group-sm', 'am-form-feedback', { 'am-form-icon am-form-error': !validator.storeName.vld }]">
                <label class="am-u-sm-12 am-u-md-2 am-form-label" for="storeName">门店名称</label>
                <div class="am-u-sm-12 am-u-md-5">
                  <am-input placeholder="门店名称" v-model="applyForm.storeName" />
                  <template v-if="!validator.storeName.vld">
                    <span class="am-icon-times"></span>
                    <small class="am-text-danger">{{ validator.storeName.msg }}</small>
                  </template>
                </div>
                <div class="am-u-end"></div>
              </div>

              <!-- 门店地址 -->
              <div :class="['am-form-group', 'am-form-group-sm', 'am-form-feedback', { 'am-form-icon am-form-error': !validator.address.vld }]">
                <label class="am-u-sm-12 am-u-md-2 am-form-label" for="address">门店地址</label>
                <div class="am-u-sm-6 am-u-md-2">
                  <select class="am-form-field" v-model="applyForm.province">
                    <option v-for="(item, index) in provinces" :key="index"
                      :value="item.province.code">{{ item.province.label }}</option>
                  </select>
                </div>
                <div class="am-u-sm-6 am-u-md-2">
                  <select class="am-form-field" v-model="applyForm.city">
                    <option v-for="(item, index) in cities" :key="index"
                      :value="item.code">{{ item.label }}</option>
                  </select>
                </div>
                <div class="am-u-sm-12 am-u-md-6">
                  <am-input placeholder="检索后可点击地图上的红色标注点" id="address" v-model="applyForm.address" />
                  <template v-if="!validator.address.vld">
                    <span class="am-icon-times"></span>
                    <small class="am-text-danger">{{ validator.address.msg }}</small>
                  </template>
                </div>
                <div class="am-u-end"></div>
              </div>

              <!-- 地图信息 -->
              <div class="am-form-group am-form-group-sm">
                <label class="am-u-sm-12 am-u-md-2 am-form-label" for="">地图信息</label>
                <div class="am-u-sm-12 am-u-md-10">
                  <bd-map
                    :center="mapProvince"
                    :location="mapCity"
                    :keyword="applyForm.address"
                    :poi.sync="poi" />
                </div>
                <div class="am-u-end"></div>
              </div>

              <!-- 提交 -->
              <div class="am-form-group am-form-group-sm">
                <div class="am-u-sm-10 am-u-sm-offset-2">
                  <am-button type="button" v-if="!submitAbled" disabled>确认提交（尚有未填写资料）</am-button>
                  <am-button type="button" @click="beforeSubmit" v-else>确认提交</am-button>
                </div>
              </div>
            </fieldset>
          </form>
        </am-col>
      </am-row>
    </am-container>
    <!-- 底部 -->
    <dg-footer />
  </main>
</template>

<script>
import Header from '@/dg_components/DgHeader'
import UploadImg from '@/components/UploadImg'
import BdMap from '@/components/BdMap'
import DgFooter from '@/views2/Footer'// 底部

export default {
  name: 'apply',
  data() {
    return {
      isPicReady: {
        smpic: false,
        pics: false
      },
      poi: {},// 地图标注信息
      applyForm: {// 报名信息
        designerID: this.$store.state.designer.designerID,
        storeName: '',// 门店名称
        storeMainPic: '',// 门店图片
        storePic: [],
        province: '',
        city: '',
        address: '',// 所属门店
        svjiaNo: '',// 三维家帐号

        lat: 39.910925,// 经纬度默认北京
        lng: 116.413384
      },

      /**
       * 非响应式属性使用
       */
      /**
       * @description - 验证字段
       */
      validator: {
        // TODO目前图片验证暂时无用
        storeMainPic: {
          count: 1,
          vld: true,
          msg: '门头照不能为空'
        },
        storePic: {
          count: 1,
          vld: true,
          msg: '门店照至少一张'
        },
        address: {
          vld: true,
          msg: '地址不能为空，可点击地图气泡标注'
        },
        svjiaNo: {
          vld: true,
          msg: '三维家帐号不能为空'
        },
        storeName: {
          vld: true,
          msg: '门店名称不能为空'
        }
      },
      provinces: [],
      storePicCount: 0,
      storeMainPicCount: 0,

      /**
       * 非响应式使用
       */
      validate: {// 字段验证逻辑，true即通过验证
        'applyForm.storeName': (val = this.applyForm.storeName) => this.validator.storeName.vld = !!val,
        'applyForm.address': (val = this.applyForm.address) => this.validator.address.vld = !!val,
        'applyForm.svjiaNo': (val = this.applyForm.svjiaNo) => this.validator.svjiaNo.vld = !!val,
        'applyForm.storeMainPic': (val = this.storeMainPicCount) => this.validator.storeMainPic.vld = (val === this.validator.storeMainPic.count),
        'applyForm.storePic': (val = this.storePicCount) => this.validator.storePic.vld = (val >= this.validator.storePic.count)
      },
      ins: void 0,

      // mapProvince: '',
      // mapCity: ''
    }
  },
  computed: {

    /**省市联动数据 */
    cities() {
      if(this.applyForm.province) {
        const obj = this.provinces.find(pro => pro.province.code === this.applyForm.province);
        return obj.cities;
      } else {
        return [];
      }
    },

    mapProvince() {
      const obj = this.provinces.find(pro => pro.province.code === this.applyForm.province);
      if(obj) {
        return obj.province.label;
      } else {
        return '';
      }
    },
    mapCity() {
      const obj = this.cities.find(city => city.code === this.applyForm.city);
      if(obj) {
        return obj.label;
      } else {
        return '';
      }
    },


    /**单一状态信息 */
    gameDetail() {
      return this.$store.state.game.detail;
    },
    gameInfo() {
      return this.$store.state.game.info;
    },
    designerID() {
      return this.$store.state.designer.designerID;
    },
    isJoin() {
      return this.$store.sate.designer.isJoin;
    },


    /**是否可以提交 */
    submitAbled() {
      if(
        this.storePicCount < this.validator.storePic.count ||
        this.storeMainPicCount !== this.validator.storeMainPic.count ||
        this.applyForm.svjiaNo === '' ||
        this.applyForm.address === ''
      ) {
        return false;
      } else {
        return this.goValidation();
      }
    },

    /**cookies */
    designerCookies() {
      return JSON.parse(this.$cookies.get('designer'));
    }
  },
  components: {
    UploadImg, BdMap,
    CHeader: Header,
    DgFooter
  },
  methods: {
    ready() {
      this.loadingPC();
      this.collpaseClose();
    },

    /**加载省市数据 */
    loadingPC() {
      return new Promise((resolve, reject) => {
        this.dgpost(this.api.PROVINCESDATA, {})
        .then(res => {
          this.provinces = res.data.data;
          resolve();
        });
      });
    },

    /**提交前的表单验证 */
    goValidation() {
      let isPass = true;// 表单是否通过所有验证
      Object.values(this.validate).forEach(fun => {
        // 提交前把所有validate走一遍
        isPass = fun() && isPass;
      });
      return isPass;
    },

    /**提交前的校验 */
    beforeSubmit() {
      this.ins = this.$loading({ loadingText: '正在上传资料，请稍等' });
      this.$refs.smpic.submit();
      this.$refs.pics.submit();
    },

    /**表单提交 */
    submit(ins) {
      this.dgpost(this.api.APPLYGAME, {
        gameID: +this.$store.state.game.info.ID,
        designerID: +this.$store.state.designer.designerID,
        storeMainPic: this.applyForm.storeMainPic,
        storePic: this.applyForm.storePic.toString(),//
        svjiaNo: this.applyForm.svjiaNo,
        province: this.applyForm.province,
        city: this.applyForm.city,
        address: this.applyForm.address,
        lat: ''+this.applyForm.lat,
        lng: ''+this.applyForm.lng,
        storeName: this.applyForm.storeName
      }).then(res => {

        // 更新设计师报名资格
        // this.$store.commit('setDesigner', {key: 'isJoin', val: 1})
        this.$store.commit('setDesignerJoin', 1);
        this.designerCookies.isJoin = 1;
        this.$cookies.set('designer', JSON.stringify(this.designerCookies), (60 * 60 * 6));
        this.ins.close();
        setTimeout(() => {
          this.$router.push('/personal');
        }, 99);
      }).catch(err => {
        this.ins.close();
        this.$message({
          title: '报名出错了',
          type: 'error',
          message: err.msg,
          closeable: true
        });
      });
    },

    /**收起大赛详细 */
    collpaseClose() {
      // setTimeout(() => $('.am-panel-hd-collapse').click(), 1999);
    }
  },
  watch: {
    poi(val) {
      this.applyForm.address = val.address;
      this.applyForm.lat = val.point.lat;
      this.applyForm.lng = val.point.lng;
    },
    'applyForm.storeName': function(val) {
      this.validate['applyForm.storeName'](val);
    },
    'applyForm.province': function(val) {
      this.applyForm.city = '';
    },
    'applyForm.svjiaNo': function(val) {
      this.validate['applyForm.svjiaNo'](val);
    },
    'applyForm.address': function(val) {
      this.validate['applyForm.address'](val);
    },

    /**
     * 替异步做法，触发提交
     */
    'applyForm.storePic': function(val) {
      this.isPicReady.smpic = this.validate['applyForm.storePic']();
    },
    'applyForm.storeMainPic': function(val) {
      this.isPicReady.pics =  this.validate['applyForm.storeMainPic']();
    },
    storeMainPicCount(val) {
      this.validate['applyForm.storeMainPic'](val);
    },
    storePicCount(val) {
      this.validate['applyForm.storePic'](val);
    },


    isPicReady: {
      handler(val) {
        console.log('****', val)
        if(val.smpic === true && val.pics === true) {
          if(this.goValidation()) {
            this.submit();
          }
        }
      },
      deep: true
    }
  },
  mounted() {
    this.ready();
  }
}
</script>

<style>
.map { width: 300px; height: 300px; }
</style>